package lazy

import "sync"

// 非线程安全的单例模式
type singleton1 struct{}

var instance1 *singleton1

func GetInstance1() *singleton1 {
	if instance1 == nil {
		instance1 = new(singleton1)
	}
	return instance1
}

// 线程安全的单例模式
type singleton2 struct{}

var (
	instance2 *singleton2
	lock      sync.Mutex
)

func GetInstance2() *singleton2 {
	lock.Lock()
	defer lock.Unlock()
	if instance2 == nil {
		instance2 = new(singleton2)
	}
	return instance2
}

// 双重检查的单例模式
type singleton3 struct{}

var instance3 *singleton3

func GetInstance3() *singleton3 {
	if instance3 == nil {
		lock.Lock()
		if instance3 == nil {
			instance3 = new(singleton3)
		}
		lock.Unlock()
	}
	return instance3
}

// 使用sync.Once的单例模式
type singleton4 struct{}

var (
	instance4 *singleton4
	once      sync.Once
)

func GetInstance4() *singleton4 {
	once.Do(func() {
		instance4 = new(singleton4)
	})
	return instance4
}
